<template>
  <div class="mall-container">
    <!-- 顶部搜索栏 -->
    <div class="search-header">
      <div class="search-box">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索商品..."
          class="search-input"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button icon="Search" @click="handleSearch" />
          </template>
        </el-input>
      </div>
      <div class="cart-icon" @click="showCart = true">
        <el-badge :value="cartCount" class="cart-badge">
          <el-icon size="24"><ShoppingCart /></el-icon>
        </el-badge>
      </div>
    </div>

    <!-- 分类导航 -->
    <div class="category-nav">
      <el-scrollbar>
        <div class="category-list">
          <div 
            class="category-item"
            :class="{ active: selectedCategory === null }"
            @click="selectCategory(null)"
          >
            全部
          </div>
          <div
            v-for="category in categories"
            :key="category.id"
            class="category-item"
            :class="{ active: selectedCategory === category.id }"
            @click="selectCategory(category.id)"
            @dblclick="goToCategoryProducts(category.id)"
          >
            {{ category.name }}
          </div>
          <div class="category-item view-all" @click="viewAllCategories">
            查看全部分类 →
          </div>
        </div>
      </el-scrollbar>
    </div>

    <!-- 商品列表 -->
    <div class="product-grid">
      <div 
        v-for="product in products"
        :key="product.id"
        class="product-card"
        @click="goToProductDetail(product.id)"
      >
        <div class="product-image">
          <el-image
            :src="product.image || '/default-product.jpg'"
            fit="cover"
            class="image"
          />
          <div class="product-actions">
            <el-button 
              circle 
              size="small" 
              :icon="product.isFavorite ? 'StarFilled' : 'Star'"
              :type="product.isFavorite ? 'danger' : 'default'"
              @click.stop="toggleFavorite(product)"
            />
          </div>
        </div>
        <div class="product-info">
          <h3 class="product-title">{{ product.name }}</h3>
          <p class="product-desc">{{ product.description }}</p>
          <div class="product-price">
            <span class="current-price">¥{{ product.price }}</span>
            <span v-if="product.originalPrice" class="original-price">¥{{ product.originalPrice }}</span>
          </div>
          <div class="product-stats">
            <span class="sales">已售{{ product.salesCount }}</span>
            <span class="rating">
              <el-rate
                v-model="product.rating"
                disabled
                show-score
                text-color="#ff9900"
                score-template="{value}"
                size="small"
              />
            </span>
          </div>
          <el-button 
            type="primary" 
            size="small" 
            class="add-cart-btn"
            @click.stop="addToCart(product)"
          >
            加入购物车
          </el-button>
        </div>
      </div>
    </div>

    <!-- 加载更多 -->
    <div v-if="hasMore" class="load-more">
      <el-button @click="loadMore" :loading="loading">加载更多</el-button>
    </div>

    <!-- 购物车抽屉 -->
    <el-drawer
      v-model="showCart"
      title="购物车"
      direction="rtl"
      size="400px"
    >
      <div class="cart-content">
        <div v-if="cartItems.length === 0" class="empty-cart">
          <el-empty description="购物车是空的" />
        </div>
        <div v-else>
          <div 
            v-for="item in cartItems"
            :key="item.id"
            class="cart-item"
          >
            <el-image
              :src="item.product.image"
              fit="cover"
              class="cart-item-image"
            />
            <div class="cart-item-info">
              <h4>{{ item.product.name }}</h4>
              <p class="cart-item-price">¥{{ item.product.price }}</p>
              <div class="cart-item-controls">
                <el-input-number
                  v-model="item.quantity"
                  :min="1"
                  :max="item.product.stock"
                  size="small"
                  @change="updateCartItem(item)"
                />
                <el-button 
                  type="danger" 
                  size="small" 
                  icon="Delete"
                  @click="removeFromCart(item.id)"
                />
              </div>
            </div>
          </div>
          <div class="cart-summary">
            <div class="total-price">
              总计: ¥{{ totalPrice }}
            </div>
            <el-button type="primary" size="large" @click="goToCheckout">
              去结算
            </el-button>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { 
  getProductList, 
  getProductCategories, 
  searchProducts,
  favoriteProduct,
  unfavoriteProduct,
  getCart,
  addToCart as apiAddToCart,
  updateCartItem as apiUpdateCartItem,
  removeCartItem
} from '@/api/mall'

const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const selectedCategory = ref(null)
const categories = ref([])
const products = ref([])
const cartItems = ref([])
const showCart = ref(false)
const loading = ref(false)
const hasMore = ref(true)

// 分页参数
const pagination = reactive({
  page: 1,
  size: 20
})

// 计算属性
const cartCount = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.quantity, 0)
})

const totalPrice = computed(() => {
  return cartItems.value.reduce((total, item) => {
    return total + (item.product.price * item.quantity)
  }, 0).toFixed(2)
})

// 获取商品分类
const getCategories = async () => {
  try {
    const response = await getProductCategories()
    if (response.code === 200) {
      categories.value = response.data
    }
  } catch (error) {
    console.error('获取分类失败:', error)
  }
}

// 获取商品列表
const getProducts = async (reset = false) => {
  if (loading.value) return
  
  loading.value = true
  try {
    const params = {
      page: reset ? 1 : pagination.page,
      size: pagination.size,
      categoryId: selectedCategory.value
    }
    
    const response = await getProductList(params)
    if (response.code === 200) {
      const newProducts = response.data.records || []
      if (reset) {
        products.value = newProducts
        pagination.page = 1
      } else {
        products.value.push(...newProducts)
      }
      
      hasMore.value = newProducts.length === pagination.size
      if (!reset) {
        pagination.page++
      }
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索商品
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    getProducts(true)
    return
  }
  
  loading.value = true
  try {
    const response = await searchProducts(searchKeyword.value, {
      page: 1,
      size: pagination.size
    })
    if (response.code === 200) {
      products.value = response.data.records || []
      hasMore.value = false
    }
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败')
  } finally {
    loading.value = false
  }
}

// 选择分类
const selectCategory = (categoryId) => {
  selectedCategory.value = categoryId
  searchKeyword.value = ''
  getProducts(true)
}

// 跳转到分类商品页面
const goToCategoryProducts = (categoryId) => {
  router.push(`/mall/category/${categoryId}`)
}

// 查看全部分类
const viewAllCategories = () => {
  router.push('/mall/categories')
}

// 加载更多
const loadMore = () => {
  getProducts()
}

// 切换收藏
const toggleFavorite = async (product) => {
  try {
    if (product.isFavorite) {
      await unfavoriteProduct(product.id)
      product.isFavorite = false
      ElMessage.success('已取消收藏')
    } else {
      await favoriteProduct(product.id)
      product.isFavorite = true
      ElMessage.success('已添加收藏')
    }
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 添加到购物车
const addToCart = async (product) => {
  try {
    await apiAddToCart({
      productId: product.id,
      quantity: 1
    })
    ElMessage.success('已添加到购物车')
    loadCart()
  } catch (error) {
    console.error('添加购物车失败:', error)
    ElMessage.error('添加购物车失败')
  }
}

// 更新购物车商品
const updateCartItem = async (item) => {
  try {
    await apiUpdateCartItem(item.id, item.quantity)
  } catch (error) {
    console.error('更新失败:', error)
    ElMessage.error('更新失败')
  }
}

// 从购物车移除
const removeFromCart = async (itemId) => {
  try {
    await removeCartItem(itemId)
    ElMessage.success('已移除')
    loadCart()
  } catch (error) {
    console.error('移除失败:', error)
    ElMessage.error('移除失败')
  }
}

// 加载购物车
const loadCart = async () => {
  try {
    const response = await getCart()
    if (response.code === 200) {
      cartItems.value = response.data.items || []
    }
  } catch (error) {
    console.error('获取购物车失败:', error)
  }
}

// 跳转到商品详情
const goToProductDetail = (productId) => {
  router.push(`/mall/product/${productId}`)
}

// 跳转到结算页面
const goToCheckout = () => {
  router.push('/mall/checkout')
}

// 页面加载
onMounted(() => {
  getCategories()
  getProducts(true)
  loadCart()
})
</script>

<style lang="scss" scoped>
.mall-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.search-header {
  display: flex;
  align-items: center;
  padding: 16px;
  background: white;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  
  .search-box {
    flex: 1;
    margin-right: 16px;
    
    .search-input {
      max-width: 400px;
    }
  }
  
  .cart-icon {
    cursor: pointer;
    padding: 8px;
    
    .cart-badge {
      :deep(.el-badge__content) {
        background-color: #ff4757;
      }
    }
  }
}

.category-nav {
  background: white;
  padding: 12px 16px;
  border-bottom: 1px solid #eee;
  
  .category-list {
    display: flex;
    gap: 16px;
    
    .category-item {
      padding: 8px 16px;
      border-radius: 20px;
      background: #f8f9fa;
      cursor: pointer;
      white-space: nowrap;
      transition: all 0.3s;
      
      &:hover, &.active {
        background: #007bff;
        color: white;
      }

      &.view-all {
        color: #007bff;
        font-size: 14px;

        &:hover {
          background-color: #e3f2fd;
          color: #0056b3;
        }
      }
    }
  }
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
  padding: 16px;
}

.product-card {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  cursor: pointer;
  transition: transform 0.3s;
  
  &:hover {
    transform: translateY(-4px);
  }
  
  .product-image {
    position: relative;
    height: 200px;
    
    .image {
      width: 100%;
      height: 100%;
    }
    
    .product-actions {
      position: absolute;
      top: 8px;
      right: 8px;
    }
  }
  
  .product-info {
    padding: 16px;
    
    .product-title {
      font-size: 16px;
      font-weight: 600;
      margin: 0 0 8px 0;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    
    .product-desc {
      color: #666;
      font-size: 14px;
      margin: 0 0 12px 0;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    
    .product-price {
      margin-bottom: 8px;
      
      .current-price {
        color: #ff4757;
        font-size: 18px;
        font-weight: 600;
      }
      
      .original-price {
        color: #999;
        font-size: 14px;
        text-decoration: line-through;
        margin-left: 8px;
      }
    }
    
    .product-stats {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;
      font-size: 12px;
      color: #666;
    }
    
    .add-cart-btn {
      width: 100%;
    }
  }
}

.load-more {
  text-align: center;
  padding: 20px;
}

.cart-content {
  height: 100%;
  display: flex;
  flex-direction: column;
  
  .empty-cart {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .cart-item {
    display: flex;
    padding: 16px 0;
    border-bottom: 1px solid #eee;
    
    .cart-item-image {
      width: 60px;
      height: 60px;
      border-radius: 4px;
      margin-right: 12px;
    }
    
    .cart-item-info {
      flex: 1;
      
      h4 {
        margin: 0 0 4px 0;
        font-size: 14px;
      }
      
      .cart-item-price {
        color: #ff4757;
        font-weight: 600;
        margin: 0 0 8px 0;
      }
      
      .cart-item-controls {
        display: flex;
        align-items: center;
        gap: 8px;
      }
    }
  }
  
  .cart-summary {
    margin-top: auto;
    padding: 16px 0;
    border-top: 1px solid #eee;
    
    .total-price {
      font-size: 18px;
      font-weight: 600;
      color: #ff4757;
      margin-bottom: 16px;
      text-align: center;
    }
  }
}

@media (max-width: 768px) {
  .product-grid {
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
    gap: 8px;
    padding: 8px;
  }
  
  .search-header {
    padding: 12px;
  }
}
</style>
